package com.katesoft.scale4j.agent;

import com.katesoft.scale4j.agent.args.AgentOptions;
import com.katesoft.scale4j.agent.jmx.StopAgentOperationInvoker;
import com.katesoft.scale4j.common.lang.RuntimeUtility;
import com.katesoft.scale4j.log.LogFactory;
import com.katesoft.scale4j.log.Logger;
import com.katesoft.xml.jvmcluster.ApplicationConfigurationDocument.ApplicationConfiguration;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

/** @author kate2007 */
public class KillApp
{
    private Logger logger = LogFactory.getLogger(getClass());

    public void stop(AgentOptions options) throws Exception
    {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/jvmcluster$oxm.xml");
        ApplicationConfigurationReader reader = (ApplicationConfigurationReader) context.getBean("jvmcluster.appConfiguration.reader");
        try {
            ApplicationConfiguration configuration =
                (options.appConfigurationLocation() != null ? reader.parseConfiguration(options.appConfigurationLocation().getInputStream()) :
                    reader.parseConfiguration(new ClassPathResource(Agent.DEFAULT_LOCATION).getInputStream()));
            int jmxPort = configuration.getJmxPort().intValue();
            StopAgentOperationInvoker proxy = new StopAgentOperationInvoker(String.format("service:jmx:rmi:///jndi/rmi://localhost:%s/jmxrmi", jmxPort));
            proxy.setForceKill(options.isKill());
            proxy.invoke();
        }
        catch (Exception e) {
            logger.warn(e);
            if (RuntimeUtility.isJunit()) {
                throw e;
            }
        }
    }
}
